﻿using System.Collections;
using System.Windows.Controls;
using PeoplesJukebox.Web.Bases;
using PeoplesJukebox.Web.Entities;
using PeoplesJukebox.Web.Enums;

namespace PeoplesJukebox.Web.UserControls
{
    /// <summary>
    /// Results list user control
    /// </summary>
    public partial class ResultsList : UserControlBase           
    {
        public delegate void OnTrackSelectedEventHandler(MediaItem track);
        public delegate void OnArtistSelectedEventHandler(MediaItem artist);
        public event OnTrackSelectedEventHandler TrackSelected;
        public event OnArtistSelectedEventHandler ArtistSelected;

        private IEnumerable _results;
        
        /// <summary>
        /// Gets/sets the result source
        /// </summary>
        public IEnumerable Results
        {
            get { return this._results; }
            set
            {
                this._results = value;
                ShowResults();
            }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public ResultsList()
        {
            InitializeComponent();
            this.CatalogueServiceClient.SearchComplete += new PeoplesJukebox.Web.ServiceClients.CatalogueServiceClient.SearchCompleteEventHandler(CatalogueServiceClient_SearchComplete);
        }

        /// <summary>
        /// Clears the result list
        /// </summary>
        public void Clear()
        {
            this.Results = null;
        }

        private void CatalogueServiceClient_SearchComplete(IEnumerable results)
        {
            this.Results = results;
        }

        private void ShowResults()
        {
            this.dgResults.SelectedIndex = -1;
            this.dgResults.ItemsSource = this._results;
        }

        private void dgResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MediaItem item = this.dgResults.SelectedItem as MediaItem;
            if (item != null)
            {
                switch (item.ItemType)
                {
                    case ItemType.Album:
                        this.CatalogueServiceClient.GetAlbumTracks(item.Id);
                        break;
                    case ItemType.Artist:
                        this.CatalogueServiceClient.GetArtistTracks(item.Id);
                        if (this.ArtistSelected != null)
                        {
                            this.ArtistSelected(item);
                        }
                        break;
                    case ItemType.Track:
                        if (this.TrackSelected != null)
                        {
                            this.TrackSelected(item);
                        }
                        break;
                }
            }
        }
    }
}